import json
from PyCmpltrtok.common import sep


def check_dict_in_dict(xdict, xkey, xlimit=20):
    sep(xkey)
    cnt = 0
    for k, v in xdict[xkey].items():
        cnt += 1
        if cnt > xlimit:
            break
        print(k, ':', v)


def check_ordered_in_dict(xdict, xkey, xlimit=15, xcriteria=None):
    sep(xkey)
    cnt, no = 0, 0
    for item in xdict[xkey]:
        no += 1
        if cnt > xlimit:
            break
        if xcriteria:
            if not xcriteria(item):
                continue
        cnt += 1
        print(no, ':', item)


def check_json(json_path, xdicts_keys, xlists_keys, xcriteria=None):
    sep(json_path)
    with open(json_path, 'r', encoding='utf8') as f:
        json_obj = json.load(f)

    sep('top')
    for k in json_obj.keys():
        print(k)

    for k in xdicts_keys:
        check_dict_in_dict(json_obj, k)
    for k in xlists_keys:
        check_ordered_in_dict(json_obj, k, xcriteria=xcriteria.get(k, None) if xcriteria else None)

    return json_obj


if '__main__' == __name__:
    def _main():
        json_path = '/home/asuspei/large_data/_very_large/coco2014/annotations/captions_val2014.json'
        check_json(json_path, ['info'], ['licenses', 'images', 'annotations'])

        json_path = '/home/asuspei/large_data/_very_large/coco2014/annotations/instances_val2014.json'
        inst = check_json(
            json_path, ['info'], ['licenses', 'images', 'annotations', 'categories'],
            xcriteria={'annotations': lambda xdict: len(xdict['segmentation']) > 1},
        )
        sep('Categories of instances_val2014.json')
        check_ordered_in_dict(inst, 'categories', xlimit=50)

    _main()
